import datetime
import json

from django.db.models import Q
from django.http import JsonResponse

from celery_tasks.main import celery_app
from homes.models import House
from orders.models import Order


@celery_app.task(name='generate_order')
def generate_order(request):
    # 乐观锁在此处不适用，故改为celery
    json_dict = json.loads(request.body.decode())
    house_id = json_dict.get('house_id')
    start_date = json_dict.get('start_date')
    end_date = json_dict.get('end_date')
    # 2.整体检验，个体检验
    if not all([house_id, start_date, end_date]):
        return JsonResponse({'errno': 4103,
                             'errmsg': '缺少必传参数'})
    try:
        house = House.objects.get(id=house_id)
    except Exception as e:
        return JsonResponse({'errno': 4103,
                             'errmsg': '缺少必传参数'})
    # 将时间str转化为date类型
    try:
        start_date = datetime.date(*map(int, start_date.split('-')))
        end_date = datetime.date(*map(int, end_date.split('-')))
    except Exception as e:
        return JsonResponse({'errno': 4103,
                             'errmsg': '日期格式错误'})
    # 3.判断该时段内是否有用户已经预定
    time_range = (start_date, end_date)
    days = end_date - start_date
    days = int(str(days)[0])
    if days == 0:
        days = 1
    if days <= 0:
        return JsonResponse({'errno': 4004,
                             'errmsg': '入住时间过短'})
    if house.max_days != 0:
        if days > house.max_days:
            return JsonResponse({'errno': 4004,
                                 'errmsg': '超过最大入住天数'})
    try:
        orders = Order.objects.filter(Q(begin_date__range=time_range) & Q(end_date__range=time_range))
    except Exception as e:
        return JsonResponse({'errno': 4001,
                             'errmsg': '数据库查询错误'})
    if orders:
        test = '有数据'
        return JsonResponse({'errno': 4003,
                             'errmsg': '该时段已被预定'})

    # 4.生成订单
    user = request.user
    # order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') + ('%09d' % user.id)
    # 5.判断是否已被预定并保存数据
    try:
        order = Order.objects.create(user=user,
                                     house=house,
                                     begin_date=start_date,
                                     end_date=end_date,
                                     days=days,
                                     house_price=house.price,
                                     amount=house.price * days + house.deposit,
                                     status=Order.ORDER_STATUS["WAIT_ACCEPT"],
                                     )
    except Exception as e:
        return JsonResponse({'errno': 4001,
                             'errmsg': '创建订单失败'})
    # 6.在房屋数据表中增加订单数
    try:
        house.order_count += 1
        house.save()
    except Exception as e:
        return JsonResponse({'errno': 4001,
                             'errmsg': '增加房屋订单数量失败'})

    # 7.返回json数据
    return JsonResponse({"data": {"order_id": order.id},
                         "errno": "0",
                         "errmsg": "下单成功"})
